<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';

import { message } from 'ant-design-vue';

import CustomerSearchModal from './components/CustomerSearchModal.vue';
import EmergencyModal from './components/EmergencyModal.vue';
// 导入模态框组件
import QuickAppointmentModal from './components/QuickAppointmentModal.vue';
import TodayScheduleModal from './components/TodayScheduleModal.vue';

// 接口定义
interface Appointment {
  id: string;
  petName: string;
  ownerName: string;
  phone: string;
  appointmentTime: string;
  doctor: string;
  department: string;
  status: 'cancelled' | 'completed' | 'in-progress' | 'pending';
  description: string;
}

interface PendingItem {
  id: string;
  title: string;
  description: string;
  icon: string;
  color: string;
  type: string;
}

interface DoctorStatus {
  id: string;
  name: string;
  department: string;
  status: 'busy' | 'idle';
  currentPatient?: string;
}

// 响应式数据
const currentTime = ref('');
const currentDate = ref('');

// 模态框状态
const modals = ref({
  quickAppointment: false,
  customerSearch: false,
  todaySchedule: false,
  emergency: false,
});

// 快捷查询
const quickSearch = ref({
  petName: '',
  phone: '',
});

// 今日预约数据
const todayAppointments = ref<Appointment[]>([
  {
    id: 'A001',
    petName: '小白',
    ownerName: '张三',
    phone: '13800138001',
    appointmentTime: '09:00',
    doctor: '李医生',
    department: '内科',
    status: 'pending',
    description: '定期体检',
  },
  {
    id: 'A002',
    petName: '旺财',
    ownerName: '李四',
    phone: '13800138002',
    appointmentTime: '10:30',
    doctor: '王医生',
    department: '外科',
    status: 'in-progress',
    description: '疫苗接种',
  },
  {
    id: 'A003',
    petName: '咪咪',
    ownerName: '王五',
    phone: '13800138003',
    appointmentTime: '14:00',
    doctor: '赵医生',
    department: '皮肤科',
    status: 'pending',
    description: '皮肤病治疗',
  },
]);

// 待处理事项
const pendingItems = ref<PendingItem[]>([
  {
    id: 'P001',
    title: '检查报告待审核',
    description: '3份检查报告需要医生审核',
    icon: '📋',
    color: '#1890ff',
    type: 'report',
  },
  {
    id: 'P002',
    title: '药品库存不足',
    description: '部分常用药品库存不足',
    icon: '💊',
    color: '#faad14',
    type: 'inventory',
  },
  {
    id: 'P003',
    title: '预约确认',
    description: '5个预约需要电话确认',
    icon: '📞',
    color: '#52c41a',
    type: 'confirmation',
  },
]);

// 医生状态
const doctorStatus = ref<DoctorStatus[]>([
  {
    id: 'D001',
    name: '李医生',
    department: '内科',
    status: 'busy',
    currentPatient: '小白',
  },
  {
    id: 'D002',
    name: '王医生',
    department: '外科',
    status: 'busy',
    currentPatient: '旺财',
  },
  {
    id: 'D003',
    name: '赵医生',
    department: '皮肤科',
    status: 'idle',
  },
  {
    id: 'D004',
    name: '陈医生',
    department: '骨科',
    status: 'idle',
  },
]);

// 预约表格列定义
const appointmentColumns = [
  {
    title: '时间',
    dataIndex: 'appointmentTime',
    key: 'appointmentTime',
    width: 80,
  },
  {
    title: '宠物名称',
    dataIndex: 'petName',
    key: 'petName',
    width: 100,
  },
  {
    title: '主人',
    dataIndex: 'ownerName',
    key: 'ownerName',
    width: 100,
  },
  {
    title: '医生',
    dataIndex: 'doctor',
    key: 'doctor',
    width: 100,
  },
  {
    title: '科室',
    dataIndex: 'department',
    key: 'department',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
];

// 计算属性
const statistics = computed(() => {
  const total = todayAppointments.value.length;
  const completed = todayAppointments.value.filter(
    (a) => a.status === 'completed',
  ).length;
  const pending = todayAppointments.value.filter(
    (a) => a.status === 'pending',
  ).length;
  const emergency = 2; // 模拟紧急情况数量

  return {
    totalAppointments: total,
    completed,
    pending,
    emergency,
  };
});

// 方法
const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
  currentDate.value = now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long',
  });
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'orange',
    'in-progress': 'blue',
    completed: 'green',
    cancelled: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    'in-progress': '进行中',
    completed: '已完成',
    cancelled: '已取消',
  };
  return textMap[status] || status;
};

// 快速操作
const showQuickAppointment = () => {
  modals.value.quickAppointment = true;
};

const showCustomerSearch = () => {
  modals.value.customerSearch = true;
};

const showTodaySchedule = () => {
  modals.value.todaySchedule = true;
};

const showEmergency = () => {
  modals.value.emergency = true;
};

// 预约相关
const startTreatment = (appointment: Appointment) => {
  message.success(`开始为 ${appointment.petName} 进行诊疗`);
  // 更新预约状态
  appointment.status = 'in-progress';
};

const viewDetails = (appointment: Appointment) => {
  message.info(`查看 ${appointment.petName} 的详细信息`);
};

const refreshAppointments = () => {
  message.success('预约数据已刷新');
};

// 待处理事项
const handlePendingItem = (item: PendingItem) => {
  message.info(`处理 ${item.title}`);
};

// 快捷查询
const quickSearchPet = () => {
  if (quickSearch.value.petName) {
    message.info(`查询宠物: ${quickSearch.value.petName}`);
    // 这里可以打开查询结果模态框
  } else {
    message.warning('请输入宠物名称或编号');
  }
};

const quickSearchCustomer = () => {
  if (quickSearch.value.phone) {
    message.info(`查询主人手机号: ${quickSearch.value.phone}`);
    // 这里可以打开查询结果模态框
  } else {
    message.warning('请输入主人手机号');
  }
};

// 模态框回调
const handleAppointmentSuccess = () => {
  message.success('预约创建成功');
  modals.value.quickAppointment = false;
};

const handleCustomerSelect = (customer: any) => {
  message.success(`已选择顾客: ${customer.name}`);
  modals.value.customerSearch = false;
};

// 生命周期
let timeInterval: NodeJS.Timeout;

onMounted(() => {
  updateTime();
  timeInterval = setInterval(updateTime, 1000);
});

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval);
  }
});
</script>

<template>
  <div class="pet-hospital-portal">
    <!-- 快速操作区域 -->
    <div class="quick-actions">
      <a-row :gutter="24">
        <a-col :span="6">
          <div class="action-card primary" @click="showQuickAppointment">
            <div class="action-icon">📅</div>
            <div class="action-title">快速预约</div>
            <div class="action-desc">立即为宠物预约诊疗</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="action-card success" @click="showCustomerSearch">
            <div class="action-icon">🔍</div>
            <div class="action-title">顾客查询</div>
            <div class="action-desc">查询宠物和主人信息</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="action-card warning" @click="showTodaySchedule">
            <div class="action-icon">📋</div>
            <div class="action-title">今日排班</div>
            <div class="action-desc">查看今日医生排班</div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="action-card info" @click="showEmergency">
            <div class="action-icon">🚨</div>
            <div class="action-title">紧急处理</div>
            <div class="action-desc">紧急情况快速处理</div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <a-row :gutter="24">
        <!-- 左侧：今日预约和待处理 -->
        <a-col :span="16">
          <!-- 今日预约列表 -->
          <a-card title="📅 今日预约" class="content-card">
            <template #extra>
              <a-button type="link" @click="refreshAppointments">刷新</a-button>
            </template>
            <a-table
              :columns="appointmentColumns"
              :data-source="todayAppointments"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ getStatusText(record.status) }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="startTreatment(record)"
                    >
                      开始诊疗
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="viewDetails(record)"
                    >
                      查看详情
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>

          <!-- 待处理事项 -->
          <a-card title="⏰ 待处理事项" class="content-card">
            <a-list :data-source="pendingItems" size="small">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar :style="{ backgroundColor: item.color }">
                        {{ item.icon }}
                      </a-avatar>
                    </template>
                    <template #title>
                      <span>{{ item.title }}</span>
                    </template>
                    <template #description>
                      <span>{{ item.description }}</span>
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <a-button
                      type="link"
                      size="small"
                      @click="handlePendingItem(item)"
                    >
                      处理
                    </a-button>
                  </template>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </a-col>

        <!-- 右侧：统计信息和快捷功能 -->
        <a-col :span="8">
          <!-- 今日统计 -->
          <a-card title="📊 今日统计" class="content-card">
            <div class="statistics">
              <div class="stat-item">
                <div class="stat-number">
                  {{ statistics.totalAppointments }}
                </div>
                <div class="stat-label">总预约</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ statistics.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ statistics.pending }}</div>
                <div class="stat-label">待处理</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ statistics.emergency }}</div>
                <div class="stat-label">紧急</div>
              </div>
            </div>
          </a-card>

          <!-- 快捷查询 -->
          <a-card title="🔍 快捷查询" class="content-card">
            <a-form layout="vertical" size="small">
              <a-form-item label="宠物名称/编号">
                <a-input
                  v-model:value="quickSearch.petName"
                  placeholder="输入宠物名称或编号"
                  @keyup.enter="quickSearchPet"
                />
              </a-form-item>
              <a-form-item label="主人手机号">
                <a-input
                  v-model:value="quickSearch.phone"
                  placeholder="输入主人手机号"
                  @keyup.enter="quickSearchCustomer"
                />
              </a-form-item>
              <a-form-item>
                <a-space>
                  <a-button type="primary" @click="quickSearchPet">
                    查询宠物
                  </a-button>
                  <a-button @click="quickSearchCustomer">查询主人</a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </a-card>

          <!-- 医生状态 -->
          <a-card title="👨‍⚕️ 医生状态" class="content-card">
            <a-list :data-source="doctorStatus" size="small">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar
                        :style="{
                          backgroundColor:
                            item.status === 'busy' ? '#ff4d4f' : '#52c41a',
                        }"
                      >
                        {{ item.name.charAt(0) }}
                      </a-avatar>
                    </template>
                    <template #title>
                      <span>{{ item.name }}</span>
                    </template>
                    <template #description>
                      <a-tag
                        :color="item.status === 'busy' ? 'red' : 'green'"
                        size="small"
                      >
                        {{ item.status === 'busy' ? '忙碌' : '空闲' }}
                      </a-tag>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 模态框组件 -->
    <QuickAppointmentModal
      v-model:visible="modals.quickAppointment"
      @success="handleAppointmentSuccess"
    />
    <CustomerSearchModal
      v-model:visible="modals.customerSearch"
      @select="handleCustomerSelect"
    />
    <TodayScheduleModal v-model:visible="modals.todaySchedule" />
    <EmergencyModal v-model:visible="modals.emergency" />
  </div>
</template>

<style scoped>
.pet-hospital-portal {
  min-height: 100vh;
  padding: 24px;
}

.portal-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  background: rgb(255 255 255 / 95%);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgb(0 0 0 / 10%);
  backdrop-filter: blur(10px);
}

.hospital-info h1 {
  margin: 0 0 8px;
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
}

.hospital-info p {
  margin: 0;
  font-size: 16px;
  color: #7f8c8d;
}

.current-time {
  text-align: right;
}

.time {
  margin-bottom: 4px;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.date {
  font-size: 14px;
  color: #7f8c8d;
}

.quick-actions {
  margin-bottom: 24px;
}

.action-card {
  padding: 24px;
  text-align: center;
  cursor: pointer;
  background: rgb(255 255 255 / 95%);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgb(0 0 0 / 10%);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.action-card:hover {
  box-shadow: 0 8px 24px rgb(0 0 0 / 15%);
  transform: translateY(-4px);
}

.action-card.primary {
  border-left: 4px solid #1890ff;
}

.action-card.success {
  border-left: 4px solid #52c41a;
}

.action-card.warning {
  border-left: 4px solid #faad14;
}

.action-card.info {
  border-left: 4px solid #722ed1;
}

.action-icon {
  margin-bottom: 12px;
  font-size: 32px;
}

.action-title {
  margin-bottom: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.action-desc {
  font-size: 14px;
  color: #7f8c8d;
}

.main-content {
  margin-bottom: 24px;
}

.content-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgb(0 0 0 / 10%);
}

.statistics {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.stat-item {
  padding: 16px;
  text-align: center;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  margin-bottom: 4px;
  font-size: 24px;
  font-weight: 700;
  color: #1890ff;
}

.stat-label {
  font-size: 12px;
  color: #7f8c8d;
}

:deep(.ant-card-head) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background: #fafafa;
}

:deep(.ant-list-item) {
  padding: 12px 0;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
